﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Sunny.UI;
using LogisticsAndong.Model;
using System.Threading;
using LogisticsAndong.Business;
using LogisticsAndong.Comm;
using LeederGlobal;

namespace LogisticsAndong.Forms
{
    public partial class FrmProgressDirection : UIPage
    {
        AutoSizeFormClass asc = new AutoSizeFormClass();

        MaterialDirectionBLL bllMaterialDirection = new MaterialDirectionBLL();
        LogisticsAndongBusiness logisticsAndongBusiness;

        /// <summary>
        /// 开捆状态
        /// </summary>
        CancellationTokenSource cancel_KKStatuscontrol;

        /// <summary>
        /// 判断窗体是否首次加载
        /// </summary>
        bool isLoad = true;     

        public FrmProgressDirection()
        {
            InitializeComponent();

            //初始化服务
            logisticsAndongBusiness = LogisticsAndongBusiness.CreateInstance();
            logisticsAndongBusiness.LipChangeEvent += sysjUiUpdate_event;
            logisticsAndongBusiness.LsdChangeEvent += lsdUiUpdate_event;
            //dgvDateSet();
        }

        private void FrmProgressDirection_Load(object sender, EventArgs e)
        {
            //如果窗体已经加载过则不重新加载
            if (!isLoad)
                return;
            isLoad = false;

            //顺引顺建内制品
            dgvDMSY.AutoGenerateColumns = false;
            dgvDMSY.AllowUserToAddRows = false;
            dgvDMSY.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvDMSY.ReadOnly = true;
            dgvDMSY.AddColumn("序号", "ID", 10);
            dgvDMSY.AddColumn("工程名称", "MaterialName", 45);
            dgvDMSY.AddColumn("剩余台数", "LeftCount", 45);

            dgvXMSY.AutoGenerateColumns = false;
            dgvXMSY.AllowUserToAddRows = false;
            dgvXMSY.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvXMSY.ReadOnly = true;
            dgvXMSY.AddColumn("序号", "ID", 10);
            dgvXMSY.AddColumn("工程名称", "MaterialName", 45);
            dgvXMSY.AddColumn("剩余台数", "LeftCount", 45);

            dgvZWSJ.AutoGenerateColumns = false;
            dgvZWSJ.AllowUserToAddRows = false;
            dgvZWSJ.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvZWSJ.ReadOnly = true;
            dgvZWSJ.AddColumn("序号", "ID", 10);
            dgvZWSJ.AddColumn("工程名称", "MaterialName", 45);
            dgvZWSJ.AddColumn("剩余台数", "LeftCount", 45);

            dgvNZP.AutoGenerateColumns = false;
            dgvNZP.AllowUserToAddRows = false;
            dgvNZP.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvNZP.ReadOnly = true;
            dgvNZP.AddColumn("序号", "ID", 10);
            dgvNZP.AddColumn("工程名称", "MaterialName", 45);
            dgvNZP.AddColumn("剩余台数", "LeftCount", 45);
            dgvNZP.AddColumn("工程台数", "ProjectCount", 45);

            dgvPX.AutoGenerateColumns = false;
            dgvPX.AllowUserToAddRows = false;
            dgvPX.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvPX.ReadOnly = true;
            dgvPX.AddColumn("序号", "ID", 10);
            dgvPX.AddColumn("工程名称", "MaterialName", 45);
            dgvPX.AddColumn("剩余台数", "LeftCount", 45);

            //拉绳灯
            dgvRDCFL.AutoGenerateColumns = false;
            dgvRDCFL.AllowUserToAddRows = false;
            dgvRDCFL.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvRDCFL.ReadOnly = true;
            dgvRDCFL.AddColumn("序号", "Id", 10);
            dgvRDCFL.AddColumn("工程名称", "PullingRopeName", 20);
            dgvRDCFL.AddColumn("拉绳", "PullShow", 20);
            dgvRDCFL.AddColumn("绿灯", "GreenShow", 25);
            dgvRDCFL.AddColumn("红灯", "RedShow", 25);

            dgvTJSHZGCFL.AutoGenerateColumns = false;
            dgvTJSHZGCFL.AllowUserToAddRows = false;
            dgvTJSHZGCFL.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvTJSHZGCFL.ReadOnly = true;
            dgvTJSHZGCFL.AddColumn("序号", "Id", 10);
            dgvTJSHZGCFL.AddColumn("工程名称", "PullingRopeName", 20);
            dgvTJSHZGCFL.AddColumn("拉绳", "PullShow", 20);
            dgvTJSHZGCFL.AddColumn("绿灯", "GreenShow", 25);
            dgvTJSHZGCFL.AddColumn("红灯", "RedShow", 25);

            dgvPCJHCFL.AutoGenerateColumns = false;
            dgvPCJHCFL.AllowUserToAddRows = false;
            dgvPCJHCFL.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvPCJHCFL.ReadOnly = true;
            dgvPCJHCFL.AddColumn("序号", "Id", 10);
            dgvPCJHCFL.AddColumn("工程名称", "PullingRopeName", 20);
            dgvPCJHCFL.AddColumn("拉绳", "PullShow", 20);
            dgvPCJHCFL.AddColumn("绿灯", "GreenShow", 25);
            dgvPCJHCFL.AddColumn("红灯", "RedShow", 25);

            dgvFXDWCFL.AutoGenerateColumns = false;
            dgvFXDWCFL.AllowUserToAddRows = false;
            dgvFXDWCFL.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvFXDWCFL.ReadOnly = true;
            dgvFXDWCFL.AddColumn("序号", "Id", 10);
            dgvFXDWCFL.AddColumn("工程名称", "PullingRopeName", 20);
            dgvFXDWCFL.AddColumn("拉绳", "PullShow", 20);
            dgvFXDWCFL.AddColumn("绿灯", "GreenShow", 25);
            dgvFXDWCFL.AddColumn("红灯", "RedShow", 25);

            dgvCXDWCFL.AutoGenerateColumns = false;
            dgvCXDWCFL.AllowUserToAddRows = false;
            dgvCXDWCFL.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvCXDWCFL.ReadOnly = true;
            dgvCXDWCFL.AddColumn("序号", "Id", 10);
            dgvCXDWCFL.AddColumn("工程名称", "PullingRopeName", 20);
            dgvCXDWCFL.AddColumn("拉绳", "PullShow", 20);
            dgvCXDWCFL.AddColumn("绿灯", "GreenShow", 25);
            dgvCXDWCFL.AddColumn("红灯", "RedShow", 25);

            dgvXWCFL.AutoGenerateColumns = false;
            dgvXWCFL.AllowUserToAddRows = false;
            dgvXWCFL.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvXWCFL.ReadOnly = true;
            dgvXWCFL.AddColumn("序号", "Id", 10);
            dgvXWCFL.AddColumn("工程名称", "PullingRopeName", 20);
            dgvXWCFL.AddColumn("拉绳", "PullShow", 20);
            dgvXWCFL.AddColumn("绿灯", "GreenShow", 25);
            dgvXWCFL.AddColumn("红灯", "RedShow", 25);

            //timer1.Start();
            //timer2.Start();
            sysjUiUpdate();
            lsdUiUpdate();

            //开启线程绑定数据
            cancel_KKStatuscontrol = new CancellationTokenSource();
            Task.Factory.StartNew(() =>
            {
                KKStatusCommand();
            }, cancel_KKStatuscontrol.Token);
        }

        private void FrmProgressDirection_SizeChanged(object sender, EventArgs e)
        {
            //asc.controllInitializeSize(this);
        }

        public void UpdateCells(UIDataGridView dgv)
        {
            if (dgv.Rows.Count > 0)
                dgv.Rows[0].Selected = false;

            foreach (DataGridViewRow item in dgv.Rows)
            {
                SignalLampShowModel model = item.DataBoundItem as SignalLampShowModel;
                if (model.IsPull == 1)
                    item.Cells["拉绳"].Style.BackColor = Color.Gray;
                else
                    item.Cells["拉绳"].Style.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(102)))));
                if (model.IsGreen == 1)
                    item.Cells["绿灯"].Style.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(176)))), ((int)(((byte)(80)))));
                else
                    item.Cells["绿灯"].Style.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(102)))));
                if (model.IsRed == 1)
                    item.Cells["红灯"].Style.BackColor = Color.Red;
                else
                    item.Cells["红灯"].Style.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(102)))));

            }
            //dgv.Update();
        }


        /// <summary>
        /// 开捆指示更新
        /// </summary>
        private async void KKStatusCommand()
        {
            while (!this.cancel_KKStatuscontrol.Token.IsCancellationRequested)
            {
                foreach (UnpackingDirectionShowModel model in GolbalVariable.UnpackingDirectionModelBag)
                {
                    UpdateUI(model);
                }
                await Task.Delay(1000);
            }
        }

        /// <summary>
        /// 更新数据
        /// </summary>
        private void UpdateUI(UnpackingDirectionShowModel unpackingDirectionModel)
        {
            try
            {
                if (this.labelrdcount.InvokeRequired)
                {
                    try
                    {
                        this.Invoke(new MethodInvoker(() =>
                        {
                            UpdateUIDATA(unpackingDirectionModel);
                        }));
                    }
                    catch (Exception ex)
                    {

                    }
                }
                else
                    UpdateUIDATA(unpackingDirectionModel);
            }
            catch (Exception ex)
            {

            }
        }

        /// <summary>
        /// 更新界面数据
        /// </summary>
        private void UpdateUIDATA(UnpackingDirectionShowModel unpackingDirectionModel)
        {
            var control = this.tableLayoutPanel1.Controls.Find(unpackingDirectionModel.ControlName, true);
            if (control != null && control.Length > 0)
            {
                Label la = control[0] as Label;
                la.Text = unpackingDirectionModel.UnpackingCount.ToString();
            }
        }

        /// <summary>
        /// 修改部品剩余数量输入框
        /// </summary>
        /// <param name="entityMaterialDirection">部品对象</param>
        private void materialDirectionEdit(MaterialDirectionModel entityMaterialDirection)
        {
            UIEditOption option = new UIEditOption();
            //UILocalize.OK = "保存";
            option.AutoLabelWidth = true;
            option.Text = "剩余台数修改(" + entityMaterialDirection.MaterialName + ")";
            option.AddInteger("LeftCount", "剩余台数", entityMaterialDirection.LeftCount, true);

            UIEditForm frm = new UIEditForm(option);
            frm.ShowDialog();

            if (frm.IsOK)
            {
                entityMaterialDirection.LeftCount = int.Parse(frm["LeftCount"].ToString());
                bllMaterialDirection.Update(entityMaterialDirection);
                //NLoggerHelper.INFO("顺引顺建/内制品/排序工程剩余台数手动修改(" + entityMaterialDirection.MaterialName + ":" + entityMaterialDirection.LeftCount + ")");
                UIMessageTip.ShowOk("修改成功");
            }
            //UILocalize.OK = "确定";
            frm.Dispose();
        }

        /// <summary>
        /// 东面顺建双击列表事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvDMSY_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (ApplicationCache.CurrentUser.Permission == 0)
                materialDirectionEdit(dgvDMSY.CurrentRow.DataBoundItem as MaterialDirectionModel);
            else
                UIMessageBox.Show("该操作需要管理员权限，请先切换管理员账号！");

        }
        /// <summary>
        /// 西面顺建双击列表事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvXMSY_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (ApplicationCache.CurrentUser.Permission == 0)
                materialDirectionEdit(dgvXMSY.CurrentRow.DataBoundItem as MaterialDirectionModel);
            else
                UIMessageBox.Show("该操作需要管理员权限，请先切换管理员账号！");
        }
        /// <summary>
        /// 中物顺建双击列表事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvZWSJ_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (ApplicationCache.CurrentUser.Permission == 0)
                materialDirectionEdit(dgvZWSJ.CurrentRow.DataBoundItem as MaterialDirectionModel);
            else
                UIMessageBox.Show("该操作需要管理员权限，请先切换管理员账号！");
        }
        /// <summary>
        /// 内制品双击列表事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvNZP_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (ApplicationCache.CurrentUser.Permission == 0)
                materialDirectionEdit(dgvNZP.CurrentRow.DataBoundItem as MaterialDirectionModel);
            else
                UIMessageBox.Show("该操作需要管理员权限，请先切换管理员账号！");
        }
        /// <summary>
        /// 排序工程双击列表事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvPX_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (ApplicationCache.CurrentUser.Permission == 0)
                materialDirectionEdit(dgvPX.CurrentRow.DataBoundItem as MaterialDirectionModel);
            else
                UIMessageBox.Show("该操作需要管理员权限，请先切换管理员账号！");
        }

        private void sysjUiUpdate_event()
        {
            sysjUiUpdate();
        }

        private void lsdUiUpdate_event()
        {
            lsdUiUpdate();
        }

        private void sysjUiUpdate()
        {
            this.Invoke(new MethodInvoker(() =>
            {
                dgvDMSY.DataSource = null;
                dgvDMSY.DataSource = GolbalVariable.MaterialDirectionBag.Where(x => x.TypeId == 1).OrderBy(x => x.ID).ToList();
                dgvXMSY.DataSource = null;
                dgvXMSY.DataSource = GolbalVariable.MaterialDirectionBag.Where(x => x.TypeId == 2).OrderBy(x => x.ID).ToList();
                dgvZWSJ.DataSource = null;
                dgvZWSJ.DataSource = GolbalVariable.MaterialDirectionBag.Where(x => x.TypeId == 3).OrderBy(x => x.ID).ToList();
                dgvNZP.DataSource = null;
                dgvNZP.DataSource = GolbalVariable.MaterialDirectionBag.Where(x => x.TypeId == 4).OrderBy(x => x.ID).ToList();
                dgvPX.DataSource = null;
                dgvPX.DataSource = GolbalVariable.MaterialDirectionBag.Where(x => x.TypeId == 5).OrderBy(x => x.ID).ToList();
            }));
        }

        private void lsdUiUpdate()
        {
            this.Invoke(new MethodInvoker(() =>
            {
                dgvRDCFL.DataSource = null;
                dgvRDCFL.DataSource = GolbalVariable.SignalLampShowModelBag.Where(x => x.TypeId == 1).OrderBy(x => x.Id).ToList();
                dgvTJSHZGCFL.DataSource = null;
                dgvTJSHZGCFL.DataSource = GolbalVariable.SignalLampShowModelBag.Where(x => x.TypeId == 2).OrderBy(x => x.Id).ToList();
                dgvPCJHCFL.DataSource = null;
                dgvPCJHCFL.DataSource = GolbalVariable.SignalLampShowModelBag.Where(x => x.TypeId == 3).OrderBy(x => x.Id).ToList();
                dgvFXDWCFL.DataSource = null;
                dgvFXDWCFL.DataSource = GolbalVariable.SignalLampShowModelBag.Where(x => x.TypeId == 4).OrderBy(x => x.Id).ToList();
                dgvCXDWCFL.DataSource = null;
                dgvCXDWCFL.DataSource = GolbalVariable.SignalLampShowModelBag.Where(x => x.TypeId == 5).OrderBy(x => x.Id).ToList();
                dgvXWCFL.DataSource = null;
                dgvXWCFL.DataSource = GolbalVariable.SignalLampShowModelBag.Where(x => x.TypeId == 6).OrderBy(x => x.Id).ToList();
                
                UpdateCells(dgvRDCFL);
                UpdateCells(dgvTJSHZGCFL);
                UpdateCells(dgvPCJHCFL);
                UpdateCells(dgvFXDWCFL);
                UpdateCells(dgvCXDWCFL);
                UpdateCells(dgvXWCFL);
            }));
        }

        private void FrmProgressDirection_FormClosing(object sender, FormClosingEventArgs e)
        {
            Thread thread;
            foreach (var cd in GolbalVariable.SignalLampBlinkThreadDictionary)
            {
                thread = cd.Value;
                if (GolbalVariable.SignalLampBlinkThreadDictionary.TryRemove(cd.Key, out thread))
                {
                    thread.Abort();
                }
            }
            cancel_KKStatuscontrol.Cancel();
            logisticsAndongBusiness.cancel_specialProject.Cancel();
            logisticsAndongBusiness.cancel_mainequip.Cancel();
        }

        private void FrmProgressDirection_FormClosed(object sender, FormClosedEventArgs e)
        {
        }
    }
}
